import type { MenuInfo } from 'rc-menu/lib/interface'
import { LogoutOutlined } from '@ant-design/icons'
import { history } from '@umijs/max'
import React, { useCallback } from 'react'
import HeaderDropdown from '../HeaderDropdown'
import { clearAll, getUserInfo } from '@/utils/auth'

export interface GlobalHeaderRightProps {
  menu?: boolean
  children?: React.ReactNode
}

export function AvatarName() {
  const userInfo = getUserInfo()
  return <span className="anticon" style={{ cursor: 'pointer' }}>{userInfo?.name}</span>
}

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ children }) => {

  const runLogout = () => {
    clearAll()
    history.push('/login')
  }

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event
      if (key === 'logout') {
        runLogout()
        return
      }
    },
    [runLogout]
  )

  const menuItems = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录'
    }
  ]

  return (
    <>
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems
        }}
      >
        {children}
      </HeaderDropdown>
    </>
  )
}
